package com.ldc.commonres.common

import android.app.Activity
import android.content.pm.ActivityInfo
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.launcher.ARouter
import com.ldc.commonres.views.CommonDialogLoading
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope

abstract class ActivityBase : AppCompatActivity(), CoroutineScope by MainScope() {

    protected val TAG: String = "【%s】".format(this::class.java.name)
    open var activity: Activity? = null

    // 消息处理器
    private val callback = Handler.Callback { p0 -> processMessage(p0) }
    private val handler: Handler = Handler(Looper.getMainLooper(), callback)


    // 对话框
    private var loadDialog: CommonDialogLoading? = null

    // 消息分发
    open fun processMessage(msg: Message): Boolean {
        return false
    }

    // 获取消息处理器
    fun getHandler(): Handler = handler

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        try {
            activity = this
            ARouter.getInstance().inject(this)
            loadDialog = CommonDialogLoading(this)
            // 禁用横屏
            requestedOrientation = ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED
            setContentView(loadView())
            start(savedInstanceState)
            main()
        } catch (e: Exception) {
            processError(e)
        }
    }

    open fun loadView(): View? = null
    open fun start(savedInstanceState: Bundle?) {}
    abstract fun main()
    open fun processError(e: Exception) {
        e.printStackTrace()
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacksAndMessages(null)
    }

    fun showLoadDialog(str: String = "加载中，请稍等···") {
        loadDialog?.let {
            it.setText(str)
            if (!it.isShowing) {
                it.show()
            }
        }
    }

    fun dismissLoadDialog() {
        loadDialog?.dismiss()
    }

}